import { defineStore } from 'pinia';
import { fishDistributionApi } from '@/api';

export const useFishDistributionStore = defineStore('fishDistribution', {
  state: () => ({
    distributions: [],
    loading: false,
    error: null
  }),
  
  actions: {
    async fetchDistributions() {
      this.loading = true;
      try {
        const response = await fishDistributionApi.getAll();
        this.distributions = response.data || [];
        this.loading = false;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
      }
    },
    
    async addDistribution(distribution) {
      this.loading = true;
      try {
        const response = await fishDistributionApi.add(distribution);
        // 添加成功后，将新数据添加到列表前面
        // this.distributions.unshift(response.data);
        this.loading = false;
        return response.data;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    },
    
    async updateDistribution(id, updatedDistribution) {
      this.loading = true;
      try {
        const response = await fishDistributionApi.update(id, updatedDistribution);
        // 更新成功后，更新本地数据
        // const index = this.distributions.findIndex(dist => dist.id === id);
        // if (index !== -1) {
        //   this.distributions[index] = { ...this.distributions[index], ...response.data };
        // }
        this.loading = false;
        return response.data;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    },
    
    async deleteDistribution(id) {
      this.loading = true;
      try {
        await fishDistributionApi.delete(id);
        // 删除成功后，从列表中移除
        // this.distributions = this.distributions.filter(dist => dist.id !== id);
        this.loading = false;
      } catch (error) {
        this.error = error.message;
        this.loading = false;
        throw error;
      }
    }
  }
}); 